package com.sy.core.intercepter;

import com.sy.core.model.SyShoppingCart;
import com.sy.core.model.SyUserInfo;
import com.sy.core.model.SysUser;
import com.sy.core.util.CookUtils;
import com.sy.core.util.RedisUtil;
import com.sy.core.web.BaseCtl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;


/**
 * 登录拦截器
 *
 * @Author :Chong.CaiXin
 * @Description :
 * @Date : Created in 13:25 2018/9/4
 */
public class LoginIntercepter extends BaseCtl implements HandlerInterceptor {
    @Resource
    protected RedisTemplate<Object, Object> template;

    /**
     * Action执行前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
       try {
            String  requestUri = request.getRequestURI();
            String  loginUrl = (StringUtils.isNotBlank(requestUri) && requestUri.indexOf("back")!=-1)?"/back/login":"/website/login";
            String userId = new CookUtils().getLoginUserId(request);
            if (StringUtils.isNotBlank(userId)) {
                SysUser sys = StringUtils.isBlank(userId) ? null : RedisUtil.getFormRedis(template, userId);
                if (sys != null) {
                    if(!"1".equalsIgnoreCase((String)sys.getUd5())){//非后台账户
                        if(loginUrl.indexOf("back")!=-1){
                            response.getWriter().write("当前账号无法执行此操作,请联系管理员");
                            response.sendRedirect(loginUrl);
                            return false;
                        }else{
                            return true;
                        }
                    }
                    return true;
                }else{
                    response.sendRedirect(loginUrl);
                    return false;
                }
            } else {
                response.sendRedirect(loginUrl);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * Action执行后，View渲染前调用
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    /**
     * View渲染后调用，整个流程执行结束调用
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}

